<?php
class Front_Model_MenuMapper {
	protected $_dbTable;

	public function __construct() {

	}

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Front_Model_DbTable_Menu');
		}
		return $this->_dbTable;
	}



	public function populateMenuFromArray($array, Front_Model_Menu $menuModel) {
		$menuModel->_mid = $array['mid'];
		$menuModel->_menuname = $array['menuname'];
		$menuModel->_description = $array['description'];
		$menuModel->_menuimage = $array['menuimage'];
	}

	public function populateMenuFromRow(Zend_Db_Table_Row_Abstract $row, Front_Model_Menu $menuModel) {
		$menuModel->_mid = $row->mid;
		$menuModel->_menuname = $row->menuname;
		$menuModel->_description = $row->description;
		$menuModel->_menuimage = $row->menuimage;
	}


	public function save(Front_Model_Menu $menuInfo)
	{
		$mid = $menuInfo->_mid;
		$data = array(
			'mid' => $menuInfo->_mid,
            'description'   => $menuInfo->_description,
            'menuname' => $menuInfo->_menuname,
            'menuimage' => $menuInfo->_menuimage
		);

		if (!isset($mid)) {
			unset($data['mid']);
			return $this->getDbTable()->insert($data);
		} else {
			return $this->getDbTable()->update($data, array('mid = ?' => $mid));
		}
	}

	public function find($mid, Front_Model_Menu $menuInfo)
	{
		$result = $this->getDbTable()->find($mid);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$this->populateMenuFromRow($row, $menuInfo);
		return $row;
	}

	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Front_Model_Menu();
			$this->populateMenuFromRow($row, $entry);
			$entries[] = $entry;
		}
		return $entries;
	}

	public function delete($mid)
	{
		$result = $this->getDbTable()->find($mid);
		if (0 == count($result)) {
			return;
		}
		return $this->getDbTable()->delete(array('mid = ?' => $mid));
	}
}